<?php


namespace App\Listener;


use App\Common\Utils\ResponseUtils;
use Lexik\Bundle\JWTAuthenticationBundle\Event\AuthenticationFailureEvent;
use Lexik\Bundle\JWTAuthenticationBundle\Event\AuthenticationSuccessEvent;
use Lexik\Bundle\JWTAuthenticationBundle\Event\JWTExpiredEvent;
use Lexik\Bundle\JWTAuthenticationBundle\Event\JWTInvalidEvent;
use Lexik\Bundle\JWTAuthenticationBundle\Event\JWTNotFoundEvent;
use Lexik\Bundle\JWTAuthenticationBundle\Response\JWTAuthenticationFailureResponse;
use Symfony\Component\HttpFoundation\Response;

class JWTAuthorizeListener
{

    /**
     * @param AuthenticationSuccessEvent $event
     */
    public function onAuthenticationSuccessResponse(AuthenticationSuccessEvent $event)
    {
        $data = $event->getData();
        $data['user'] = $event->getUser()->jsonSerialize();
        $event->setData([
            'success' => true,
            'code' => 0,
            'message' => '授权成功',
            'data' => $data
        ]);

    }

    /**
     * @param AuthenticationFailureEvent $event
     */
    public function onAuthenticationFailureResponse(AuthenticationFailureEvent $event)
    {
        $response = ResponseUtils::error($event->getResponse()->getStatusCode(),
            "授权失败，请确认账号是否正确", Response::HTTP_UNAUTHORIZED);

        $event->setResponse($response);
    }

    /**
     * @param JWTInvalidEvent $event
     */
    public function onJWTInvalid(JWTInvalidEvent $event)
    {
        $response = ResponseUtils::error($event->getResponse()->getStatusCode(),
            "非法请求，token验证失败", Response::HTTP_FORBIDDEN);

        $event->setResponse($response);
    }

    /**
     * @param JWTNotFoundEvent $event
     */
    public function onJWTNotFound(JWTNotFoundEvent $event)
    {
        $response = ResponseUtils::error($event->getResponse()->getStatusCode(),
            "非法请求，token缺失", Response::HTTP_UNAUTHORIZED);

        $event->setResponse($response);
    }

    /**
     * @param JWTExpiredEvent $event
     */
    public function onJWTExpired(JWTExpiredEvent $event)
    {
        /** @var JWTAuthenticationFailureResponse */
        $response = ResponseUtils::error($event->getResponse()->getStatusCode(),
            "token已过期", Response::HTTP_FORBIDDEN);

        $event->setResponse($response);
    }
}